package com.ulook.lookplanet.util.mgc;


import org.springframework.stereotype.Component;
import java.util.*;

/**
 * 描述：初始化敏感词库,就是搭建一个仓库
 *
 * @author L1998
 * @date 2021/5/26
 */
@Component
public class SensitiveWordInit {
    /**
     * 创建敏感词库
     */
    private HashMap sensitiveWordMap;

    /**
     * 初始化敏感词库
     */
    public Map initSensitiveWord(List<String> sensitiveWordList) {
        try {
            //遍历List集合对象,并将敏感词去重存储到set集合中
            HashSet<String> sensitiveWordSet = new HashSet<>();
            for (String sensitiveWord : sensitiveWordList) {
                //截取掉首尾空格将敏感词添加进去
                sensitiveWordSet.add(sensitiveWord.trim());
            }
            this.addSensitiveWord2Map(sensitiveWordSet);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sensitiveWordMap;
    }

    /**
     * 将敏感词汇添加到词库容器sensitiveWordMap中;
     * @param sensitiveWordSet
     */
    private void addSensitiveWord2Map(Set<String> sensitiveWordSet) {
        //初始化敏感词库的大小
        sensitiveWordMap = new HashMap(sensitiveWordSet.size());
        //初始化敏感词为null
        String key = null;
        //初始化当前敏感词库为null
        Map nowMap = null;
        //初始化辅助敏感词库
        Map<String, String> newMap = null;
        //迭代器遍历敏感词Set集合
        Iterator<String> iterator = sensitiveWordSet.iterator();
        while (iterator.hasNext()) {
            //赋值key敏感词
            key = iterator.next();
            //nowMap地址指向sensitiveWordMap
            nowMap = sensitiveWordMap;
            //遍历敏感词长度
            for (int i = 0; i < key.length(); i++) {
                //取出第i个char
                char keyChar = key.charAt(i);
                //判断该char是不是已经存在与当前词库中
                Object wordMap = nowMap.get(keyChar);
                if (wordMap != null) {
                    //存在,用此wordMap替换nowMap
                    nowMap = (Map) wordMap;
                } else {
                    //不存在就在nowMap中存(key是keyChar,value是)
                    newMap = new HashMap<String, String>();
                    newMap.put("isEnd", "0");
                    nowMap.put(keyChar, newMap);
                    nowMap = newMap;
                }
                //如果当前char是敏感词的最后一个字,存放标识为结尾字
                if (i == key.length() - 1) {
                    nowMap.put("isEnd", "1");
                }
                //输出查看敏感词存储过程
                // System.out.println("敏感词存储过程" + sensitiveWordMap);
            }
            //查看最终敏感词存放结构
            // System.out.println("最终数据" + sensitiveWordMap);
        }
    }

}
